package net.wicp.tams.common.spring.connector.quartz;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;

import lombok.extern.slf4j.Slf4j;
import net.wicp.tams.common.Result;
import net.wicp.tams.common.apiext.StringUtil;
import net.wicp.tams.common.connector.beans.CusDynaBean;
import net.wicp.tams.common.connector.executor.IBusiApp;
import net.wicp.tams.common.constant.dic.YesOrNo;
import net.wicp.tams.common.exception.ProjectException;
import net.wicp.tams.common.spring.quartz.JobTaskService;
import net.wicp.tams.common.spring.quartz.bean.ScheduleJob;

@Service(value = "quartz.add")
@Slf4j
@ConditionalOnProperty(name = "common.spring.quartz.enable", havingValue = "true")
public class QuartzAdd implements IBusiApp {
	@Autowired
	private JobTaskService jobTaskService;

	@Override
	public CusDynaBean exe(CusDynaBean inputBean, CusDynaBean outBeanOri) throws ProjectException {
		String jobName = inputBean.getStrValueByName("jobName");
		String jobGroup = inputBean.getStrValueByName("jobGroup");
		String cronExpression = inputBean.getStrValueByName("cronExpression");
		String springName = inputBean.getStrValueByName("springName");
		String beanClass = inputBean.getStrValueByName("beanClass");
		String description = inputBean.getStrValueByName("description");
		YesOrNo isActiv = inputBean.getByType(YesOrNo.class, "isActiv");
		YesOrNo isConcurrent = inputBean.getByType(YesOrNo.class, "isConcurrent");
		if (StringUtil.isNull(springName) && StringUtil.isNull(beanClass)) {
			log.error("springName与beanClass二者必须填一个");
			outBeanOri.setResult(Result.getError("springName与beanClass二者必须填一个"));
			return outBeanOri;
		}
		ScheduleJob scheduleJob = jobTaskService.getTaskByGroupAndName(jobGroup, jobName);
		if (scheduleJob != null) {
			outBeanOri.setResult(Result.getError("任务已存在"));
			return outBeanOri;
		}
		ScheduleJob addobj = new ScheduleJob();
		addobj.setJobName(jobName);
		addobj.setJobGroup(jobGroup);
		addobj.setCronExpression(cronExpression);
		addobj.setSpringName(springName);
		addobj.setBeanClass(beanClass);
		addobj.setDescription(description);
		addobj.setIsActiv(isActiv);
		addobj.setIsConcurrent(isConcurrent);
		Result ret = jobTaskService.addTask(addobj);
		outBeanOri.setResult(ret);
		ScheduleJob doAfter = jobTaskService.getTaskByGroupAndName(jobGroup, jobName);
		outBeanOri.set("jobId", doAfter.getId());
		return outBeanOri;
	}
}
